package com.powerunion.datacollection.web.struts;

import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.apache.struts.upload.FormFile;

import com.powerunion.datacollection.config.ConfigUtil;
import com.powerunion.datacollection.model.Accessories;
import com.powerunion.datacollection.model.ApproveWorkItem;
import com.powerunion.datacollection.service.AccessoriesManager;
import com.powerunion.datacollection.service.ApproveWorkItemManager;
import com.powerunion.datacollection.transaction.Transaction;
import com.powerunion.datacollection.transaction.TransactionHelper;
import com.powerunion.util.StringUtils;
import com.powerunion.util.log.LogHelper;

public class AccessoriesAction extends DispatchAction {

	private static final Logger logger = LogHelper.getInstance().getLogger(
			AccessoriesAction.class);
	private AccessoriesManager am = null;

	public AccessoriesAction() {
		super();
		this.am = new AccessoriesManager();
	}

	public void finalize() throws Throwable {
		this.am = null;
		super.finalize();
	}

	public ActionForward getTemplateAccessories(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String documentId = request.getParameter("formId");
		String accessories = this.am.getAccessoriesByFormId(documentId);

		logger.debug("getTemplateAccessories:" + accessories);
		response.setContentType("text/json;charset=utf-8");
		try {
			response.getWriter().print(accessories);
		} catch (IOException e) {
			logger.error("输出json失败", e);
			return null;
		}
		return null;
	}

	public ActionForward getAccessoriesBySubmi(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String documentId = request.getParameter("formId");
		String submiUser = request.getRemoteUser();
		String procId = request.getParameter("procId");
		String actId = request.getParameter("actId");

		String accessories = this.am.getAccessoriesBySubmi(documentId,
				submiUser, procId, actId);

		logger.debug("getAccessoriesBySubmi:" + accessories);
		response.setContentType("text/json;charset=utf-8");
		try {
			response.getWriter().print(accessories);
		} catch (IOException e) {
			logger.error("输出json失败", e);
			return null;
		}
		return null;
	}

	// public ActionForward getAccessoriesBySubwork(ActionMapping mapping,
	// ActionForm form,
	// HttpServletRequest request, HttpServletResponse response)
	// throws Exception {
	// String documentId = request.getParameter("formId");
	// String procId = request.getParameter("procId");
	// String approveId = request.getParameter("actId");
	//		
	// String accessories = this.am.getAccessories4SubWork(documentId, procId,
	// approveId);
	//		
	// logger.debug("getAccessoriesBySubwork:"+accessories);
	// response.setContentType("text/json;charset=utf-8");
	// try {
	// response.getWriter().print(accessories);
	// } catch (IOException e) {
	// logger.error("输出json失败",e);
	// return null;
	// }
	// return null;
	// }

	public ActionForward getAccessories4AllSubWork(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String documentId = request.getParameter("formId");
		String procId = request.getParameter("procId");
		String approveId = request.getParameter("approveId");
		String actId = request.getParameter("actId");
		int flag = Integer.parseInt(request.getParameter("flag"));

		String result = "";
		if (flag == 2) {// 获取该审批步骤下所有的上报数据
			// 获取整合后的数据
			result = this.am.getAccessories4AllSubWork(documentId, procId,
					actId);

		} else {
			ApproveWorkItemManager awi = new ApproveWorkItemManager();
			ApproveWorkItem awit = awi.getByKey(approveId);
			int preActType = awit.getPreActType();
			if (preActType == 1) {// 当前上报的步骤为审批步骤
				result = this.am.getAccessories4AllSubWork(documentId, procId,
						awit.getPreActId());
			} else {// 当前上报的步骤为采集步骤
				result = this.am.getAccessories4SubWork(documentId, procId,
						approveId);
			}
		}
		logger.debug("getAccessories4AllSubWork:" + result);
		response.setContentType("text/json;charset=utf-8");
		try {
			response.getWriter().print(result);
		} catch (IOException e) {
			logger.error("输出json失败", e);
			return null;
		}
		return null;
	}

	public ActionForward delete(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		String[] ids = StringUtils.split(request.getParameter("codes"), ",");

		Transaction transaction = null;

		response.setContentType("text/json;charset=utf-8");
		try {
			transaction = TransactionHelper.getTransaction();
			transaction.begin();

			boolean flag = this.am.delete(ids);

			if (flag == true) {
				response.getWriter().print("{success:true}");
			} else {
				response.getWriter().write("{failure:true}");
			}
			transaction.commit();
		} catch (Exception e) {
			try {
				transaction.rollback();
			} catch (Exception e1) {
				logger.error("", e);
				throw e;
			} finally {
				transaction = null;
				response.getWriter().write("{failure:true}");
			}
		}
		return null;
	}

	public ActionForward save(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		AccessoriesForm accessoriesForm = (AccessoriesForm) form;
		String procId = request.getParameter("procId");
		String submiUser = request.getRemoteUser();
		String actId = request.getParameter("actId");
		String formId = request.getParameter("formId");
		int itemplate = request.getParameter("itemplate") == "" ? 0 : Integer
				.parseInt(request.getParameter("itemplate"));

		String sizeControlStr = ConfigUtil.getInstance().getParameter(
				"upload_file_size");
		int sizeControl = Integer.parseInt(sizeControlStr) * 1024* 1024;

		FormFile file = accessoriesForm.getFile();
		response.setContentType("text/html;charset=utf-8");
		if (file == null) {
			response.getWriter().print("{success:false,message:'上传数据为空！'}");
			return null;
		} else {
			logger.debug("file.getFileSize():"+file.getFileSize());
			if (file.getFileSize()/(1024*1024) > sizeControl) {
				response.getWriter().print(
						"{success:false,message:'上传的文件超出了规定的" + sizeControlStr
								+ "M大小！'}");
				return null;
			} else
			{
				Transaction transaction = null;
				try {
					transaction = TransactionHelper.getTransaction();
					transaction.begin();
					Accessories accessories = new Accessories();
					accessories.setFilename(file.getFileName());
					accessories.setFileContent(file.getInputStream());
					accessories.setActId(actId);
					accessories.setFormId(formId);
					accessories.setSubmiUser(submiUser);
					accessories.setProcId(procId);
					accessories.setItemplate(itemplate);

					boolean flag = am.save(accessories);
					if (flag) {
						response.getWriter().print(
								"{success:true,message:'上传成功'}");
					} else {
						response.getWriter().print(
								"{success:false,message:'上传失败'}");
					}

					transaction.commit();
				} catch (Exception e) {
					try {
						transaction.rollback();
					} catch (Exception e1) {
						logger.error("", e);
						throw e;
					} finally {
						transaction = null;
					}
				}
			}
		}
		return null;
	}

}
